
package net.sourceforge.simcpux;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;

import com.avos.avoscloud.AVObject;
import com.greenantmall.R;
import com.greenantmall.utils.PayCompleteListener;
import com.greenantmall.utils.iLog;
import com.greenantmall.wxapi.PayActivity;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

import java.util.List;

public class WeChatPayUtil implements IWXAPIEventHandler {

    private IWXAPI api;
    private final String TAG = "";
    private Activity mContext;
    public PayCompleteListener mPayCompletListener;
    public List<AVObject> mCreatedOrdersList;
    static WeChatPayUtil weChatPayUtil;

    public static WeChatPayUtil getInstance() {

        if (weChatPayUtil == null) {
            weChatPayUtil = new WeChatPayUtil();
        }
        return weChatPayUtil;
    }

    public WeChatPayUtil() {

    }

    public void setData(Activity mContext, List<AVObject> mCreatedOrdersList,
            PayCompleteListener mPayCompletListener) {
        this.mContext = mContext;
        this.mPayCompletListener = mPayCompletListener;
        this.mCreatedOrdersList = mCreatedOrdersList;

    }

    public void wechatPay() {

        if (mContext != null) {
            Intent intent = new Intent(mContext, PayActivity.class);
            mContext.startActivity(intent);
        }

    }

    @Override

    public void onReq(BaseReq arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onResp(BaseResp resp) {
        iLog.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        /**
         * 0 成功 展示成功页面 -1 错误
         * 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。 -2 用户取消
         * 无需处理。发生场景：用户不支付了，点击取消，返回APP。
         */
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == 0) {
                wechatPay();
                if (mCreatedOrdersList == null || mCreatedOrdersList.size() == 0) {
                    // success
                    if (mPayCompletListener != null) {
                        mPayCompletListener.payComplete();
                    }
                }

            } else if (resp.errCode == -1) {
                // fail

            } else if (resp.errCode == -2) {
                // cancel

            }

            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(R.string.app_tip);
            builder.setMessage(mContext.getString(R.string.pay_result_callback_msg,
                    String.valueOf(resp.errCode)));
            builder.show();
        }
    }

}
